package org.vsg.common.pagination.web.taglibs;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vsg.common.pagination.AdvancedPagination;
import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.wrapper.AdvancedGenericWebSortByPaginationWrapper;

/**
 * JSP Tag Handler class
 *
 * @jsp.tag   name = "GroupingOfPage"
 *            display-name = "Name for GroupingOfPage"
 *            description = "Description for GroupingOfPage"
 *            body-content = "JSP"
 */
public class GroupingOfPageTag extends BodyTagSupport {

	final static Logger logger = LoggerFactory.getLogger(FirstGroupingTag.class);
	
	private int maxPage;
	
	private int pageIndexNum;	
	
	private PaginationBarTag parent;
	
	
	public GroupingOfPageTag() {
		// TODO Auto-generated constructor stub
	}
	
	
	public int doStartTag() throws JspException {
		parent = (PaginationBarTag)this.findAncestorWithClass(this,PaginationBarTag.class);
		
		if (parent == null) {
			throw new JspException("Element \"groupingOfPage\" must set in the element \"paginationBar\"! ");
		}
		
		Pagination page = parent.getPagination();
		int pageNum = 0;
		
		if (!(page instanceof AdvancedPagination)) {
			logger.warn("The Advanced Pagination is not supported!");
			maxPage = 0;
			pageIndexNum = 0;			
		} else {
			AdvancedPagination apage = (AdvancedPagination)page;
			int[] pages = apage.getGroupingOfPageIndex(apage.getGroupingIndex());
			if (pages != null) {
				pageIndexNum = pages[0];
				maxPage = pages[pages.length-1];
			}
		}
		
		Object wrapper = pageContext.getAttribute(parent.getId());		
		StringBuffer pageNumberUrl = new StringBuffer();
		
		if (wrapper instanceof AdvancedGenericWebSortByPaginationWrapper) {
			AdvancedGenericWebSortByPaginationWrapper webWrapper = (AdvancedGenericWebSortByPaginationWrapper)wrapper;

			// get the total record is not empty
			if (page.getTotalRecord() > 0) {
				pageNumberUrl.append(webWrapper.getNumPageUrl(pageIndexNum));
				pageIndexNum++;
			} else {
				pageNumberUrl.append(webWrapper.getNumPageUrl(pageIndexNum));
			}
			
			pageContext.setAttribute("pageNumber",new Integer(pageIndexNum));
			pageContext.setAttribute("pageNumberUrl", pageNumberUrl.toString());
		
		}		
		
		return BodyTagSupport.EVAL_BODY_BUFFERED;
	}
	
	public int doAfterBody() throws JspException {
		int returnValue = Tag.SKIP_BODY;
		if (this.bodyContent != null) {
			JspWriter write = this.bodyContent.getEnclosingWriter();
			try {
				write.write(this.bodyContent.getString());
			} catch (Exception e) {
				throw new JspException(e);				
			}
			this.bodyContent.clearBody();			
		}

		if (pageIndexNum >= maxPage) {
			returnValue = Tag.SKIP_BODY;
		} else {
			
			Object wrapper = pageContext.getAttribute(parent.getId());
			StringBuffer pageNumberUrl = new StringBuffer();			
			int pageNum = 0;
			
			if (wrapper instanceof AdvancedGenericWebSortByPaginationWrapper) {
				AdvancedGenericWebSortByPaginationWrapper webWrapper = (AdvancedGenericWebSortByPaginationWrapper)wrapper;
				pageNum = webWrapper.getNumPage(pageIndexNum);
	
				pageNumberUrl.append(webWrapper.getNumPageUrl(pageIndexNum));
				
				pageContext.setAttribute("pageNumber",new Integer(pageIndexNum));
				pageContext.setAttribute("pageNumberUrl", pageNumberUrl.toString());

			}			
			pageIndexNum++;

			returnValue = IterationTag.EVAL_BODY_AGAIN;					
		}
		return returnValue;
	}

}
